//
//  MBIdleMainController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/15.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBIdleMainController.h"
#import "ZJScrollPageView.h"
#import "MBIdleAllController.h"
#import "MBIdleLocalController.h"
#import "MBLoginController.h"
#import "MBShortVideoController.h"
#import "MBIdleUserLiabilityStateModel.h"
#import <ViewDeck.h>

@interface MBIdleMainController ()<ZJScrollPageViewDelegate>
@property(nonatomic, strong)UIButton *leftNavButton;
@property(nonatomic, strong)UIButton *rightNavButton;
@property(nonatomic, strong)NSArray  *titleArray;
@property(strong, nonatomic)NSArray<NSString *> *titles;
@property(strong, nonatomic)NSArray<UIViewController<ZJScrollPageViewChildVcDelegate> *> *childVcs;
@property (weak, nonatomic) ZJScrollSegmentView *segmentView;
@property (weak, nonatomic) ZJContentView *contentView;

@end

@implementation MBIdleMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LoginState:) name:MBIsLoginNotification object:nil];
}

-(void)sendUserLiabilityStateRequest {
    NSMutableDictionary *param  = [NSMutableDictionary dictionary];
    [param setValue:filter([MBUserModel sharedMBUserModel].userInfo.userId) forKey:@"userId"];
    [param setValue:@(4) forKey:@"textId"];

    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_secondHand_userLiabilityState setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBIdleUserLiabilityStateModel *model = [MBIdleUserLiabilityStateModel mj_objectWithKeyValues:AJson];
        if ([model.userInfo.liabilityState isEqualToString:@"2"]) {
          UIAlertController *alertController = [UIAlertController alertControllerWithTitle:model.text.textTitle message:model.text.textContent preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
                [weakself.navigationController popToRootViewControllerAnimated:NO];
                [tabVC updateCurrentIndex:0];
            }];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakself sendSaveUserLiabilityStateRequest];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            [weakself presentViewController:alertController animated:YES completion:nil];
        }
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
-(void)sendSaveUserLiabilityStateRequest {
    NSMutableDictionary *param  = [NSMutableDictionary dictionary];
    [param setValue:filter([MBUserModel sharedMBUserModel].userInfo.userId) forKey:@"userId"];
    [MBHttpRequset requestWithUrl:kLive_secondHand_saveUserLiabilityState setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}


-(void)createUI {
    self.childVcs = [self setupChildVC];
    [self setupSegmentView];
    [self setupContentView];
}
-(void)createCustomNav {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightNavButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.leftNavButton];
    self.navigationItem.title = @"";
}
-(NSArray *)setupChildVC {
    MBIdleAllController *allVC = [[MBIdleAllController alloc]init];
    MBIdleLocalController *localVC = [[MBIdleLocalController alloc]init];
    NSArray *vcArray = @[allVC,localVC];
    return vcArray;
}

-(void)setupSegmentView {
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    style.showLine = YES;
    style.scrollLineColor = Color_FF8000;
    style.titleFont = kMFont(14);
    style.titleBigScale = 1.2;
    style.normalTitleColor = Color_666666;
    style.selectedTitleColor = Color_FF8000;
    // 不要滚动标题, 每个标题将平分宽度
    style.scrollTitle = YES;
    style.adjustCoverOrLineWidth = YES;
    style.titleMargin = 30.0f;
    style.autoAdjustTitlesWidth = YES;
    self.titles = self.titleArray;
    
    // 注意: 一定要避免循环引用!!
    __weak typeof(self) weakSelf = self;
    ZJScrollSegmentView *segment = [[ZJScrollSegmentView alloc] initWithFrame:CGRectMake(0, 64.0, 200, 28.0) segmentStyle:style delegate:self titles:self.titles titleDidClick:^(ZJTitleView *titleView, NSInteger index) {
        
        [weakSelf.contentView setContentOffSet:CGPointMake(weakSelf.contentView.bounds.size.width * index, 0.0) animated:YES];
        
    }];
    // 当然推荐直接设置背景图片的方式
    //    segment.backgroundImage = [UIImage imageNamed:@"extraBtnBackgroundImage"];
    
    self.segmentView = segment;
    self.navigationItem.titleView = self.segmentView;
}
-(void)setupContentView {
    ZJContentView *content = [[ZJContentView alloc] initWithFrame:self.view.frame segmentView:self.segmentView parentViewController:self delegate:self];
    self.contentView = content;
    [self.view addSubview:self.contentView];
}

- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}
- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    UIViewController<ZJScrollPageViewChildVcDelegate> *childVc = reuseViewController;
    
    if (!childVc) {
        childVc = self.childVcs[index];
    }
    
    return childVc;
}
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    //沙盒ducument目录
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //完整的文件路径
    NSString *path = [docPath stringByAppendingPathComponent:@"userModel.archive"];
    MBUserModel *userModel = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (userModel != nil) {
        [self.leftNavButton setImage:kImage(@"caIDAN") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"" forState:UIControlStateNormal];
        self.rightNavButton.hidden = NO;
    }else {
        [self.leftNavButton setImage:kImage(@"") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"登录" forState:UIControlStateNormal];
        self.rightNavButton.hidden = YES;
    }
    [self sendUserLiabilityStateRequest];

}

#pragma mark - NSNotification
-(void)LoginState:(NSNotification *)noti {
    if ([[noti.userInfo objectForKey:@"isFlag"] isEqualToString:MBLoginFLag]) {
        [self.leftNavButton setImage:kImage(@"caIDAN") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"" forState:UIControlStateNormal];
        self.rightNavButton.hidden = NO;
    }else {
        [self.leftNavButton setImage:kImage(@"") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"登录" forState:UIControlStateNormal];
        self.rightNavButton.hidden = YES;
    }
}
#pragma mark - event
-(void)leftNavButtonClick {
    MBLoginController *loginVC = [[MBLoginController alloc]init];
    [self presentViewController:loginVC animated:YES completion:nil];
}

-(void)rightNavButtonClick:(UIButton *)button {
    MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
    MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
    vc.MAX_RECORD_TIME = 11.0f;
    vc.entityType = MBShortVideoEntityTypeIdle;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)shortVideoButtonLongClick:(UILongPressGestureRecognizer *)longGest {
    if (longGest.state == UIGestureRecognizerStateBegan) {
        MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
        MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
        vc.MAX_RECORD_TIME = 30.0f;
        vc.entityType = MBShortVideoEntityTypeIdle;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - getter and setter
-(UIButton *)leftNavButton {
    if (_leftNavButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:kImage(@"") forState:UIControlStateNormal];
        [button setTitle:@"登录" forState:UIControlStateNormal];
        //        button.frame = (CGRect){{0,0},{40,40}};
        [button setTitleColor:Color_FF8000 forState:UIControlStateNormal];
        [button addTarget:self action:@selector(leftNavButtonClick) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = kFont(14);
        button.hidden = YES;
        _leftNavButton = button;
    }
    return _leftNavButton;
}

-(UIButton *)rightNavButton {
    if (_rightNavButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:kImage(@"sheyingji") forState:UIControlStateNormal];
        [button addTarget:self action:@selector(rightNavButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(shortVideoButtonLongClick:)];
        longPress.minimumPressDuration = 1.0f;
        [button addGestureRecognizer:longPress];
        _rightNavButton = button;
    }
    return _rightNavButton;
}

-(NSArray *)titleArray {
    if (_titleArray == nil) {
        _titleArray = @[@"全部",@"同城"];
    }
    return _titleArray;
}


@end
